package com.jyu.apts.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.jyu.apts.dto.ResultDto;
import com.jyu.apts.dto.TableDto;
import com.jyu.apts.dto.OrganizationDto;
import com.jyu.apts.entity.Organization;
import com.jyu.apts.service.OrganizationService;
import com.jyu.apts.utils.AliyunOSSUtil;

@RestController
public class OrganizationController {

	@Autowired
	OrganizationService organizationService;
	
	@RequestMapping("/company/{name}")
	public ModelAndView companyPage(@PathVariable("name")String name) {
		ModelAndView mv = new ModelAndView();
		Organization organization = organizationService.findByName(name);
		OrganizationDto organizationDto = new OrganizationDto().convert(organization);
		mv.addObject("organization", organizationDto);
		mv.setViewName("/company.html");
		return mv;
	}
	
	@RequestMapping("/companyMap_html")
	public ModelAndView companyMap_html() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/companyMap.html");
		return mv;
	}
	
	@RequestMapping("/getAllOrganization")
	public List<OrganizationDto> getAllOrganization() {
		List<OrganizationDto> organizationDtos = new ArrayList<OrganizationDto>();
		List<Organization> organizations = organizationService.findAll();
		organizations.forEach(organization->organizationDtos.add(new OrganizationDto().convert(organization)));
		return organizationDtos;
	}
	
	@RequiresPermissions("organization_html")
	@RequestMapping("/organization_html")
	public ModelAndView organization_html() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/organization.html");
		return mv;
	}
	
	@RequiresPermissions("organization_html")
	@RequestMapping("/addOrganization")
	public ResultDto addOrganization(String name,String province,String city,String part,MultipartFile banner,MultipartFile logo,String address,String phone,String email,String description,String latitude,String longitude) {
		if(organizationService.findByName(name)!=null)
			return new ResultDto("机构已存在",null,2);
		Organization organization = new Organization();
		organization.setProvince(province);
		organization.setCity(city);
		organization.setPart(part);
		organization.setName(name);
		if(banner != null) {
			String suffix = banner.getOriginalFilename().substring(banner.getOriginalFilename().lastIndexOf('.') + 1);
			String objectName;
			try {
				objectName = AliyunOSSUtil.upload(banner.getInputStream(), suffix);
				organization.setBanner("/oss/" + objectName);
			} catch (IOException e) {
				e.printStackTrace();
				return new ResultDto("banner图片上传失败",null,2);
			}
			
		}
		if(logo != null) {
			String suffix = logo.getOriginalFilename().substring(logo.getOriginalFilename().lastIndexOf('.') + 1);
			String objectName;
			try {
				objectName = AliyunOSSUtil.upload(logo.getInputStream(), suffix);
				organization.setLogo("/oss/" + objectName);
			} catch (IOException e) {
				e.printStackTrace();
				return new ResultDto("logo图片上传失败",null,2);
			}
		}
		organization.setAddress(address);
		organization.setPhone(phone);
		organization.setEmail(email);
		organization.setDescription(description);
		organization.setLatitude(latitude);
		organization.setLongitude(longitude);
		organizationService.save(organization);
		return new ResultDto("添加成功",null,0);
	}
	
	@RequiresPermissions("organization_html")
	@RequestMapping("/upOrganization")
	public ResultDto upOrganization(long id,String name,String province,String city,String part,MultipartFile banner,MultipartFile logo,String address,String phone,String email,String description,String latitude,String longitude,long hot) {
		Organization organization = organizationService.getOne(id);
		if(organization == null) {
			return new ResultDto("机构不存在!",null,2);
		}
		organization.setName(name);
		organization.setHot(hot);
		organization.setProvince(province);
		organization.setCity(city);
		organization.setPart(part);
		if(banner != null) {
			String oldBanner = organization.getBanner();
			if(oldBanner!=null && oldBanner.startsWith("/oss/")) {
				String oldObjectName = oldBanner.substring(5);
				AliyunOSSUtil.delete(oldObjectName);
			}
			String suffix = banner.getOriginalFilename().substring(banner.getOriginalFilename().lastIndexOf('.') + 1);
			String objectName;
			try {
				objectName = AliyunOSSUtil.upload(banner.getInputStream(), suffix);
				organization.setBanner("/oss/" + objectName);
			} catch (IOException e) {
				e.printStackTrace();
				return new ResultDto("banner图片上传失败",null,2);
			}
			
		}
		if(logo != null) {
			String oldLogo = organization.getLogo();
			if(oldLogo!=null && oldLogo.startsWith("/oss/")) {
				String oldObjectName = oldLogo.substring(5);
				AliyunOSSUtil.delete(oldObjectName);
			}
			String suffix = logo.getOriginalFilename().substring(logo.getOriginalFilename().lastIndexOf('.') + 1);
			String objectName;
			try {
				objectName = AliyunOSSUtil.upload(logo.getInputStream(), suffix);
				organization.setLogo("/oss/" + objectName);
			} catch (IOException e) {
				e.printStackTrace();
				return new ResultDto("logo图片上传失败",null,2);
			}
		}
		organization.setAddress(address);
		organization.setPhone(phone);
		organization.setEmail(email);
		organization.setDescription(description);
		organization.setLatitude(latitude);
		organization.setLongitude(longitude);
		organizationService.save(organization);
		return new ResultDto("更新成功",null,0);
	}
	
	@RequiresPermissions("organization_html")
	@RequestMapping("/delOrganization")
	public ResultDto delOrganization(String ids) {
		String[] idArray = ids.split(",");
		List<Organization> organizations = new ArrayList<Organization>();
		for(String id : idArray) {
			Organization organization = new Organization();
			organization.setId(new Long(id));
			organizations.add(organization);
		}
		organizationService.delete(organizations);
		return new ResultDto("删除成功",null,0);
	}
	
	@RequiresPermissions("organization_html")
	@RequestMapping("/getOrganizationPage")
	public TableDto<OrganizationDto> getOrganizationPage(Integer pageNumber,Integer pageSize,String search) {
		Page<Organization> pageResult = organizationService.getOrganizationPage(pageNumber, pageSize, search);
		List<Organization> organizations = pageResult.getContent();
		List<OrganizationDto> organizationDtos = new ArrayList<OrganizationDto>();
		organizations.forEach(organization->organizationDtos.add(new OrganizationDto().convert(organization)));
		return new TableDto<OrganizationDto>(organizationDtos,pageResult.getTotalElements());
	}
}
